﻿<%@ Page Language="C#" validateRequest=false%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        //Page.Response.Write("aaaa");
        Model.CommonMessage b = null;
        try
        {
            if (Page.User.Identity.Name != "")
            {
                if (string.IsNullOrEmpty(Request["txtTitle"]) || Request["txtTitle"].Trim() == "" || string.IsNullOrEmpty(Request["GroupType"])
                    || string.IsNullOrEmpty(Request["JoinOptions"]))
                {
                    b = new Model.CommonMessage(); b.State = false; b.Msg = "field";
                }
                else
                {
                    if (string.IsNullOrEmpty(Request["gid"]))
                    {
                        Add(ref b);
                    }
                    else
                    {
                        update(ref b);
                    }
                }
            }
            else
            {
                b = new Model.CommonMessage(); b.State = false; b.Msg = "login";
            }
            
        }
        catch (Exception e1) 
        {
            b = new Model.CommonMessage(); b.State = false; b.Msg = e1.Message;
        }
        
        Page.Response.Write("<script>var msgobj=" + (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(b) + ";<" + "/script>");
    }

    private void update(ref Model.CommonMessage b)
    {
        string hGuid = Request["groupID"];
        string gid = Request["gid"];
        string imgFileName = string.Empty;
        string imgFileName1 = string.Empty;
        string imgFileName2 = string.Empty;
        string imgFileName3 = string.Empty;
        //bool IsFeatured = false;
        //if (!string.IsNullOrEmpty(Request["IsFeatured"]) && Request["IsFeatured"] == "1")
        //{
        //    IsFeatured = true;
        //}
        if (Request.Files.Count > 0)
        {
            HttpPostedFile img = Request.Files[0];
            if (img.ContentLength > 0)
            {
                if (IsContentType(img.ContentType.ToLower()))
                {
                    imgFileName = "/UploadImages/Groups/" + hGuid + ".jpg";
                    imgFileName1 = "/UploadImages/Groups/" + hGuid + "_1.jpg";
                    imgFileName2 = "/UploadImages/Groups/" + hGuid + "_2.jpg";
                    imgFileName3 = "/UploadImages/Groups/" + hGuid + "_3.jpg";
                    //System.Drawing.Image oriImg = System.Drawing.Image.FromStream(img.InputStream);
                    System.Drawing.Bitmap oriImg = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(img.InputStream);
                    oriImg.Save(Server.MapPath(imgFileName), System.Drawing.Imaging.ImageFormat.Jpeg);

                    System.Drawing.Bitmap bmp1 = Convert(oriImg, new System.Drawing.Size(100, 100), System.Drawing.Color.White);
                    if (bmp1 != null) bmp1.Save(Server.MapPath(imgFileName1), System.Drawing.Imaging.ImageFormat.Jpeg);

                    System.Drawing.Bitmap bmp2 = Convert(oriImg, new System.Drawing.Size(75, 75), System.Drawing.Color.White);
                    if (bmp2 != null) bmp2.Save(Server.MapPath(imgFileName2), System.Drawing.Imaging.ImageFormat.Jpeg);

                    System.Drawing.Bitmap bmp3 = Convert(oriImg, new System.Drawing.Size(50, 50), System.Drawing.Color.White);
                    if (bmp3 != null) bmp3.Save(Server.MapPath(imgFileName3), System.Drawing.Imaging.ImageFormat.Jpeg);                    
                    bmp1.Dispose();
                    bmp2.Dispose();
                    bmp3.Dispose();
                    oriImg.Dispose();
                    ////imgFileName = "/UploadImages/Groups/" + hGuid + Path.GetExtension(img.FileName);
                    ////img.SaveAs(Server.MapPath(imgFileName));

                    //imgFileName = "/UploadImages/Groups/" + hGuid + ".jpg";
                    //System.Drawing.Image oriImg = System.Drawing.Image.FromStream(img.InputStream);
                    //Bitmap outBitmap = new Bitmap(150, 150, PixelFormat.Format24bppRgb);
                    //Graphics g = Graphics.FromImage(outBitmap);
                    //Rectangle destRectangle = new Rectangle(0, 0, 150, 150);
                    //g.DrawImage(oriImg, destRectangle);
                    //outBitmap.Save(Server.MapPath(imgFileName), System.Drawing.Imaging.ImageFormat.Jpeg);
                    //outBitmap.Dispose();
                    //oriImg.Dispose();                   
                }
            }
        }
        string groupType = Request["GroupType"];
        string learLang = groupType != "3" ? Request["learLang"] : string.Empty;
        b =
        BLF.WWW_WWW.Group.Group.UpdateGroup(gid, Request["txtTitle"], Request["txtDesc1"], groupType, learLang, Request["baseLang"], Request["JoinOptions"],
             Request["Tags"].Replace(",", " ").Replace("，", " "), imgFileName != string.Empty ? ".jpg" : imgFileName, false, Page.User.Identity.Name);
        if (b.State)
        {
            Response.Redirect("/groups/"+gid);
            return;
        }
        else
        {
            System.IO.File.Delete(imgFileName);
            System.IO.File.Delete(imgFileName1);
            System.IO.File.Delete(imgFileName2);
            System.IO.File.Delete(imgFileName3);
            Response.Write("<script>alert('Failing');history.back();<" + "/script>"); 
        }
    }

    private void Add(ref Model.CommonMessage b)
    {
        string hGuid = Guid.NewGuid().ToString("D");
        string imgFileName = string.Empty;
        string imgFileName1 = string.Empty;
        string imgFileName2 = string.Empty;
        string imgFileName3 = string.Empty;
       
        if (Request.Files.Count > 0)
        {
            HttpPostedFile img = Request.Files[0];
            if (img.ContentLength > 0)
            {
                if (IsContentType(img.ContentType.ToLower()))
                {
                    imgFileName = "/UploadImages/Groups/" + hGuid + ".jpg";
                    imgFileName1 = "/UploadImages/Groups/" + hGuid + "_1.jpg";
                    imgFileName2 = "/UploadImages/Groups/" + hGuid + "_2.jpg";
                    imgFileName3 = "/UploadImages/Groups/" + hGuid + "_3.jpg";                    
                    System.Drawing.Bitmap oriImg = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(img.InputStream);                    
                    oriImg.Save(Server.MapPath(imgFileName), System.Drawing.Imaging.ImageFormat.Jpeg);

                    System.Drawing.Bitmap bmp1 = Convert(oriImg, new System.Drawing.Size(100, 100), System.Drawing.Color.White);
                    if (bmp1 != null) bmp1.Save(Server.MapPath(imgFileName1), System.Drawing.Imaging.ImageFormat.Jpeg);
                    
                    System.Drawing.Bitmap bmp2 = Convert(oriImg, new System.Drawing.Size(75, 75), System.Drawing.Color.White);
                    if (bmp2 != null) bmp2.Save(Server.MapPath(imgFileName2), System.Drawing.Imaging.ImageFormat.Jpeg);
                    
                    System.Drawing.Bitmap bmp3 = Convert(oriImg, new System.Drawing.Size(50, 50), System.Drawing.Color.White);
                    if (bmp3 != null) bmp3.Save(Server.MapPath(imgFileName3), System.Drawing.Imaging.ImageFormat.Jpeg);
                    oriImg.Dispose();
                    bmp1.Dispose();
                    bmp2.Dispose();
                    bmp3.Dispose();
                    
                    //imgFileName = "/UploadImages/Groups/" + hGuid + Path.GetExtension(img.FileName);
                    //img.SaveAs(Server.MapPath(imgFileName));

                    //imgFileName = "/UploadImages/Groups/" + hGuid + ".jpg";
                    //System.Drawing.Image oriImg = System.Drawing.Image.FromStream(img.InputStream);
                    //Bitmap outBitmap = new Bitmap(150, 150, PixelFormat.Format24bppRgb);
                    //Graphics g = Graphics.FromImage(outBitmap);
                    //Rectangle destRectangle = new Rectangle(0, 0, 150, 150);
                    //g.DrawImage(oriImg, destRectangle);
                    //outBitmap.Save(Server.MapPath(imgFileName), System.Drawing.Imaging.ImageFormat.Jpeg);
                    //outBitmap.Dispose();
                    //oriImg.Dispose();
                }
            }
        }        
        string groupType = Request["GroupType"];
        string learLang = groupType != "3" ? Request["learLang"] : string.Empty;
        b =
        BLF.WWW_WWW.Group.Group.AddGroup(hGuid, Request["txtTitle"], Request["txtDesc"], groupType, learLang, Request["baseLang"], Request["JoinOptions"],
            Request["Tags"].Replace(",", " ").Replace("，", " "), imgFileName != string.Empty ? ".jpg" : imgFileName, false, Page.User.Identity.Name);
        if (b.State)
        {
            Response.Redirect("/groups/"+b.Msg+"?ct=1");
            //BLF.BizObject.PurgeCacheItems("Group_");
            //BLF.BizObject.PurgeCacheItems("My_Group_");
        }
        else
        {
            System.IO.File.Delete(imgFileName);
            System.IO.File.Delete(imgFileName1);
            System.IO.File.Delete(imgFileName2);
            System.IO.File.Delete(imgFileName3);
            Response.Write("<script>alert('Failing');history.back();<" + "/script>");
        }
    }    

    /// <summary>
    /// 成比例缩放图像
    /// </summary>
    /// <param name="original">原图像</param>
    /// <param name="targetSize">目标大小</param>
    /// <param name="backColor">目标背景颜色</param>
    /// <returns>缩放后的图像</returns>
    private System.Drawing.Bitmap Convert(System.Drawing.Bitmap original, System.Drawing.Size targetSize, System.Drawing.Color backColor)
    {
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(targetSize.Width, targetSize.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
        {
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.Clear(backColor);
            if (original.Width < targetSize.Width && original.Height < targetSize.Height)
            {
                g.DrawImage(original, (targetSize.Width - original.Width) / 2, (targetSize.Height - original.Height) / 2, original.Width, original.Height);
            }
            else
            {
                float targetAspect = (float)targetSize.Width / targetSize.Height; //目标比例
                float orginalAspect = (float)original.Width / original.Height;//源比例
                if (targetAspect >= orginalAspect)
                {
                    int width = (int)(((float)targetSize.Height / original.Height) * original.Width);
                    g.DrawImage(original, new System.Drawing.Rectangle((targetSize.Width - width) / 2, 0, width, targetSize.Height),
                        new System.Drawing.Rectangle(0, 0, original.Width, original.Height), System.Drawing.GraphicsUnit.Pixel);
                }
                else
                {
                    int height = (int)(((float)targetSize.Width / original.Width) * original.Height);
                    g.DrawImage(original, new System.Drawing.Rectangle(0, (targetSize.Height - height) / 2, targetSize.Width, height),
                        new System.Drawing.Rectangle(0, 0, original.Width, original.Height), System.Drawing.GraphicsUnit.Pixel);
                }
            }
        }
        return bmp;
    }
    
    /// <summary>
    /// 检查图片类列
    /// </summary>
    /// <param name="strCon">图片内容</param>
    /// <returns>bool</returns>
    private bool IsContentType(string strCon)
    {
        string[] arrC = { "jpg", "jpeg", "gif", "png" };
        bool flag = false;
        for (int i = 0; i < arrC.Length; i++)
        {
            if (strCon.IndexOf(arrC[i]) > 0)
            {
                flag = true;
                break;
            }
        }
        return flag;
    }
</script>
<script type="text/javascript">
window.parent.CallBack(msgobj);
</script>